package kg.aibek.projecteuler.p10;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Problem32 {
	public void solve() {
		List<Integer> nList = new ArrayList<Integer>();
		for (int i = 1; i < 10; i++) {
			nList.add(i);
		}
		List<String> sList = getPermutation(nList);

		Set<Integer> products = new HashSet<Integer>();
		for (String str : sList) {
			if (isPandigital(str, products)) {
				System.out.println(str);
			}
		}

		int sum = 0;
		for (Integer i : products) {
			sum += i;
		}

		System.out.println(sum);
	}

	private boolean isPandigital(String str, Set<Integer> set) {
		for (int i = 1; i < str.length() - 2; i++) {
			for (int j = i + 1; j < str.length() - 1; j++) {
				int a = new Integer(str.substring(0, i));
				int b = new Integer(str.substring(i, j));
				int c = new Integer(str.substring(j));

				if (a * b == c) {
					set.add(c);
					System.out.println(a + " * " + b + " = " + c);
					return true;
				}
			}
		}

		return false;
	}

	private List<String> getPermutation(List<Integer> nList) {
		List<String> ssList = new ArrayList<String>();
		if (nList.size() == 0) {
			ssList.add("");
			return ssList;
		}

		for (Integer i : nList) {
			String s = i + "";
			List<Integer> nnList = new ArrayList<Integer>();
			nnList.addAll(nList);
			nnList.remove(i);
			List<String> sList = getPermutation(nnList);
			for (String str : sList) {
				ssList.add(s + str);
			}
		}

		return ssList;
	}

	public static void main(String[] args) {
		Problem32 p = new Problem32();
		p.solve();
	}
}
